<template>
  <div>
    <table>
      <thead>
      <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>总次数</th>
        <th>提交天数</th>
        <th v-for="date in dateList" :key="date">{{ date }}</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(student, index) in studentTableData" :key="student.studentNumber"
          :class="{'even-row': index % 2 === 1}">
        <td>{{ student.studentNumber }}</td>
        <td>{{ student.name }}</td>
        <td>{{ student.totalCount }}</td>
        <td>{{ student.daysCount }}</td>
        <td v-for="date in dateList" :key="date">{{ student.dateCounts[date] || 0 }}</td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import {getStudent} from '@/utils/api.js'
import {onMounted, ref} from 'vue'

const studentData = ref([])
const studentTableData = ref([])
const dateList = ref([])

onMounted(() => {
  getStudent().then(res => {
    studentData.value = res.data.flat() // 展平嵌套数组
    processTableData()
  })
})

const processTableData = () => {
  const dataMap = {}
  const allDates = new Set()

  studentData.value.forEach(student => {
    if (!dataMap[student.studentNumber]) {
      dataMap[student.studentNumber] = {
        studentNumber: student.studentNumber,
        name: student.name,
        dateCounts: {},
        totalCount: 0,
        daysCount: 0
      }
    }
    if (student.info) {
      const date = new Date(student.info).toISOString().split('T')[0].slice(5) // 去掉年份
      if (!dataMap[student.studentNumber].dateCounts[date]) {
        dataMap[student.studentNumber].dateCounts[date] = 0
      }
      if (dataMap[student.studentNumber].dateCounts[date] === 0) {
        dataMap[student.studentNumber].daysCount += 1
      }
      dataMap[student.studentNumber].dateCounts[date] += 1
      dataMap[student.studentNumber].totalCount += 1
      allDates.add(date)
    }
  })

  dateList.value = Array.from(allDates).sort()
  studentTableData.value = Object.values(dataMap).sort((a, b) => a.studentNumber - b.studentNumber)
}
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
}

th {
  background-color: #f0f8ff;
  text-align: center;
}

td {
  text-align: center;
}

/* 隔行变色样式 */
tr:nth-child(even) {
  background-color: #f0f8ff; /* 较为明显的背景色，示例为淡蓝色 */
}
</style>
